﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Text.RegularExpressions;

namespace MensUnoShop.Areas.Admin.Helpers
{
    public static class PageHelper
    {
        private static string _pgname = "page";
        public static string UPager(this HtmlHelper helper, int pagesize, int currentpage, int totalitemcount)
        {
            StringBuilder sb = new StringBuilder();
            //currentpage = currentpage + 1;
            string path = HttpContext.Current.Request.Path;
            int totalpage = (int)Math.Ceiling((totalitemcount / (float)pagesize));
            if (currentpage > totalpage)
                currentpage = totalpage;
            int pagecount = (int)Math.Ceiling(totalpage / (float)10);
            int currentpagecount = currentpage % 10 == 0 ? (currentpage / 10) : (currentpage / 10) + 1;
            string qs = splitQueryString(HttpContext.Current.Request.QueryString);
            if (qs != string.Empty)
                path += "?" + qs;

            if (currentpage > 1)
                sb.AppendLine("<li><a href=\"" + makePath(path, currentpage - 1) + "\">&laquo;上一頁</a></li>");

            if (currentpagecount != 0)
            {
                for (int i = 1; i <= 10; i++)
                {
                    int j = (currentpagecount - 1) * 10 + i;
                    if (j > totalpage)
                        break;
                    if (j == currentpage)
                        sb.AppendLine("<li class=\"active\">" + j + "</li>");
                    else
                        sb.AppendLine("<li><a href=\"" + makePath(path, j) + "\">" + j + "</a>");
                }
            }
            if (currentpage < totalpage)
                sb.AppendLine("<li><a href=\"" + makePath(path, currentpage + 1) + "\">下一頁 &raquo;</a></li>");

            return sb.ToString();
        }

        private static string splitQueryString(System.Collections.Specialized.NameValueCollection qs)
        {
            string path = string.Empty;
            if (qs != null && qs.Count > 0)
            {
                foreach (var item in qs.AllKeys)
                {
                    if (item != _pgname)
                    {
                        path += item + "=" + qs[item] + "&";
                    }
                }
                if (path.Length > 0 && path.LastIndexOf("&") == path.Length - 1)
                    path = path.Remove(path.Length - 1);
            }
            return path;
        }
        private static string makePath(string path, int linktext)
        {
            if (path.IndexOf("?") > -1)
                path += "&" + _pgname + "=" + linktext.ToString();
            else
                path += "?" + _pgname + "=" + linktext.ToString();
            return path;
        }
    }
}